<template>
  <div class="page-wrap">
    <Table
      class="table"
      filter
      v-bind="tableOpts"
      defaultExpandAll
      v-on="tableEvent"
    >
      <template #operator>
        <div class="operator-wrap">
          <modifyOrder
            v-if="authority.includes(200)"
            ref="dialogRef"
            @change="fetchCurrentTable"
          />
          <modifyCAD orderType="old" ref="CADRef" @change="fetchCurrentTable" />
          <modifyAddition ref="additionRef" @change="fetchCurrentTable" />
          <modifyConfirm ref="confirmRef" @change="fetchCurrentTable" />
          <modifyPayment ref="paymentRef" @change="fetchCurrentTable" />
          <modifyRefund
            ref="refundRef"
            @change="fetchCurrentTable"
          ></modifyRefund>
          <refundDetail ref="refundDetailRef" @change="fetchCurrentTable" />
          <modifyOrderArea ref="orderAreaRef" @change="fetchCurrentTable" />
          <PaymentList ref="paymentListRef" @change="fetchCurrentTable" />
          <AdditionList ref="additionListRef" @change="fetchCurrentTable" />
          <ClassifyDetail ref="classifyDetailRef" @change="fetchCurrentTable" />
          <ParseDetail ref="ParseDetailRef" @change="fetchCurrentTable" />
          <open-pdf ref="pdf" />

          <!-- 上传安装组数 -->
          <el-dialog
            :visible.sync="upCountDialog"
            title="上传安装组数"
            center
            width="30%"
          >
            <div
              style="
                display: flex;
                align-items: center;
                justify-content: center;
              "
            >
              <el-input-number v-model="azGoodsCount"></el-input-number>
            </div>
            <span slot="footer">
              <el-button type="info" size="small" @click="upCountDialog = false"
                >取消</el-button
              >
              <el-button type="primary" size="small" @click="submitAzCount"
                >提交</el-button
              >
            </span>
          </el-dialog>
        </div>
      </template>
    </Table>
  </div>
</template>
<script>
import tableMixins from '@/mixins/tableMixins.vue'
import modifyRefund from './components/modifyRefund.vue'
import refundDetail from './components/refundDetail.vue'
import modifyOrder from './components/modifyOrder.vue'
import modifyCAD from './components/modifyCAD.vue'
import modifyAddition from './components/modifyAddition.vue'
import modifyConfirm from './components/modifyConfirm.vue'
import modifyPayment from './components/modifyPayment.vue'
import modifyOrderArea from './components/modifyOrderArea.vue'
import ParseDetail from './components/ParseDetail.vue'
import PaymentList from './PaymentList.vue'
import AdditionList from './AdditionList.vue'
import ClassifyDetail from './ClassifyDetail.vue'
import openPdf from './components/openPdf.vue'
import dayjs from 'dayjs'
import Decimal from 'decimal.js'
import { exportXlsx } from '@/utils/public.js'
import * as XLSX from 'xlsx-js-style'

export default {
  name: 'OrderManage',
  mixins: [tableMixins],
  components: {
    ParseDetail,
    openPdf,
    ClassifyDetail,
    modifyOrderArea,
    modifyAddition,
    modifyConfirm,
    AdditionList,
    modifyPayment,
    modifyOrder,
    modifyCAD,
    PaymentList,
    modifyRefund,
    refundDetail,
  },
  mounted() {
    const { authority = [] } = this.$quinn.getStorage('userData') || {}
    this.authorityRule = !authority.includes(299)
  },
  data() {
    return {
      azId: '',
      azGoodsCount: '',
      upCountDialog: false,
      authorityRule: false,
      apiName: 'orderList',
      form: {
        storeName: {
          tag: 'el-input',
          label: '订单名称',
          value: '',
          props: {
            clearable: true,
            placeholder: '请输入订单名称',
          },
        },
        creatorName: {
          tag: 'el-input',
          label: '创建人名称',
          value: '',
          props: {
            clearable: true,
            placeholder: '请输入创建人名称',
          },
        },
        // areaId: {
        //   tag: "el-select",
        //   label: "区域",
        //   value: "",
        //   items: this.getArea(),
        //   props: {
        //     clearable: true,
        //     filterable: true,
        //   },
        // },
        // areaId: {
        //   tag: 'el-select',
        //   label: '区域',
        //   value: '',
        //   items: [
        //     {label: '西安2仓', value: 56},
        //     {label: '山西仓', value: 58},
        //   ],
        //   props: {
        //     clearable: true,
        //   },
        // },
        // areaId: {
        //   tag: "el-select",
        //   label: "区域",
        //   value: "",
        //   items: [
        //     {label: '西安2仓', value: 56},
        //     {label: '山西仓', value: 58},
        //   ],
        //   props: {},
        // },
        cadName: {
          tag: 'el-input',
          label: 'CAD操作人员',
          value: '',
          props: {
            clearable: true,
            placeholder: '请输入CAD操作人员名称',
          },
        },
        areaId: this.formArea(),
        outStatus: {
          tag: 'el-select',
          label: '出库状态',
          value: -1,
          items: [
            { label: '全部', value: -1 },
            { label: '待出库', value: 0 },
            { label: '部分出库', value: 1 },
            { label: '全部出库', value: 2 },
          ],
          props: {},
        },
        orderType: {
          tag: 'el-select',
          label: '订单类型',
          value: 1,
          items: [
            { label: '新增店铺', value: 1 },
            { label: '老店升级', value: 2 },
          ],
          props: {},
        },
        isDebt: {
          tag: 'el-select',
          label: '是否欠款',
          value: '',
          items: [
            { label: '欠款', value: 0 },
            { label: '已结清', value: 1 },
          ],
          props: {
            clearable: true,
          },
        },
        // delivery: {
        //   tag: "el-date-picker",
        //   label: "发货日期",
        //   value: "",
        //   props: {
        //     clearable: true,
        //     placeholder: "请选择发货日期",
        //     pickerOptions: {
        //       // disabledDate (time) {
        //       // 	return time.getTime() < dayjs().startOf("day").valueOf();
        //       // },
        //     },
        //   },
        // },
        orderBy: {
          tag: 'el-select',
          label: '排序规则',
          value: 1,
          items: [
            { label: '默认排序', value: 1 },
            { label: '发货日期', value: 2 },
            { label: '修改时间', value: 3 },
          ],
          props: {},
        },
        startTime: {
          tag: 'el-date-picker',
          label: '开始日期',
          value: '',
          props: {
            clearable: true,
            placeholder: '请选择开始日期',
            pickerOptions: {
              // disabledDate (time) {
              // 	return time.getTime() < dayjs().startOf("day").valueOf();
              // },
            },
          },
        },
        endTime: {
          tag: 'el-date-picker',
          label: '结束日期',
          value: '',
          props: {
            clearable: true,
            placeholder: '请选择结束日期',
            pickerOptions: {
              // disabledDate (time) {
              // 	return time.getTime() < dayjs().startOf("day").valueOf();
              // },
            },
          },
        },
      },
    }
  },
  computed: {
    authority() {
      const { authority = [] } = this.$quinn.getStorage('userData') || {}
      return authority || []
    },
  },
  methods: {
    formatQuery(params) {
      if (!params.orderBy) delete params.orderBy
      try {
        // const d = dayjs(params.delivery);
        const s = dayjs(params.startTime)
        const e = dayjs(params.endTime)
        // if (d.isValid()) params.deliveryDate = d.format("YYYY-MM-DD");
        if (s.isValid()) params.startTime = s.format('YYYY-MM-DD')
        if (e.isValid()) params.endTime = e.format('YYYY-MM-DD')
      } catch (e) {
        console.log(e)
      }
      if (params.outStatus == -1) delete params.outStatus
      return params
    },
    mergeSameCells(ws, data, colIndex, startRow = 2) {
      let merges = ws['!merges'] || []
      let prevValue = null
      for (let row = startRow; row < data.length; row++) {
        const value = data[row][colIndex]
        if (value === prevValue) {
          // 扩展上一段合并范围
          merges[merges.length - 1].e.r = row
        } else {
          prevValue = value
          merges.push({
            s: { r: row, c: colIndex },
            e: { r: row, c: colIndex },
          })
        }
      }
      ws['!merges'] = merges
    },
    submitAzCount() {
      const data = {
        orderId: this.azId,
        azGoodsCount: this.azGoodsCount,
      }
      this.$api.orderUpdateAzGoodsCount(data).then((res) => {
        if (res == 1) {
          this.$message.success('提交成功！')
          this.upCountDialog = false
          this.azGoodsCount = ''
          window.location.reload()
        }
      })
    },
    handleAction(opts, row) {
      console.log('点击按钮')

      const { storeName: name, id, area } = row
      let ref = null
      const map = {
        CAD: 'CADRef',
        addition: 'additionRef',
        additionList: 'additionListRef',
        payment: 'paymentRef',
        paymentList: 'paymentListRef',
        area: 'orderAreaRef',
        refund: 'refundRef',
        refundDetail: 'refundDetailRef',
      }
      if (opts === 'uploadCount') {
        this.azId = row.id
        this.azGoodsCount = ''
        this.upCountDialog = true
      }
      if (opts === 'edit') return this.showDialog(opts, row)
      else if (opts === 'exportWarehouseOrder') {
        let params = {
          orderId: row.id,
          type: 1,
        }
        this.$api.orderGetOfferDirectoryDown(params).then((res) => {
          if (res.length == 0) {
            this.$message('暂无报货单数据!')
            return
          }
          if (!row.expressCharge) row.expressCharge = 0
          const wb = XLSX.utils.book_new()
          let data = [
            ['赵一鸣门店货架报价清单'],
            [''],
            ['门店名称:', '', '门店负责人：'],
            ['产品名称', '规格', '单价', '总价', '数量'],
          ]
          res.map((el) => {
            data.push([
              el.directoryName,
              el.norms,
              el.directoryFee,
              el.money,
              el.directoryCount,
            ])
          })

          data.push(['运费（元/公里）：'])
          data.push(['', '', '', '合计：', ''])
          const ws = XLSX.utils.aoa_to_sheet(data)
          ws['!cols'] = [
            { wpx: 250 }, // 第一列宽度为100单位
            { wpx: 150 },
            { wpx: 100 },
            { wpx: 100 },
            { wpx: 100 },
            { wpx: 100 },
            { wpx: 100 },
          ]
          ws['!rows'] = [
            { hpt: 15 }, // 第0行 大标题（合并了两行，所以高度大一些）
            { hpt: 15 }, // 第1行 （大标题合并区域第二行）
            { hpt: 30 }, // 第2行 门店信息
            { hpt: 25 }, // 第3行 表头
          ]
          for (let i = 4; i < data.length; i++) {
            ws['!rows'][i] = { hpt: 30 }
          }
          ws['A1'].s = {
            alignment: { horizontal: 'center' },
            font: { bold: true, sz: 20, color: { rgb: '000000' } },
            // fill: {fgColor: {rgb: ''}}
          }
          ws['A1'].hpt = 140
          XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')
          ws['!merges'] = [
            { s: { r: 0, c: 0 }, e: { r: 1, c: 4 } },
            { s: { r: 2, c: 0 }, e: { r: 2, c: 1 } }, // “门店名称”合并两列
            { s: { r: 2, c: 2 }, e: { r: 2, c: 3 } }, // “门店负责人”合并两列
          ]
          const range = XLSX.utils.decode_range(ws['!ref']) // 获取工作表范围
          for (let R = range.s.r; R <= range.e.r; R++) {
            for (let C = range.s.c; C <= range.e.c; C++) {
              const cellAddress = { r: R, c: C } // 获取单元格地址
              const cell = ws[XLSX.utils.encode_cell(cellAddress)]
              if (cell) {
                cell.s = cell.s || {} // 初始化样式
                cell.s.alignment = {
                  horizontal: 'center', // 水平居中
                  vertical: 'center', // 垂直居中
                }
              }
            }
          }
          this.mergeSameCells(ws, data, 0)
          const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'binary' })
          // 创建一个 Blob 对象
          const blob = new Blob([s2ab(wbout)], {
            type: 'application/octet-stream',
          })
          // 使用 Blob 对象创建一个链接
          const link = document.createElement('a')
          link.href = URL.createObjectURL(blob)
          link.download = `${row.storeName}报价单.xlsx`

          // 触发下载
          link.click()

          // 清理
          URL.revokeObjectURL(link.href)

          function s2ab(s) {
            const buf = new ArrayBuffer(s.length)
            const view = new Uint8Array(buf)
            for (let i = 0; i !== s.length; ++i)
              view[i] = s.charCodeAt(i) & 0xff
            return buf
          }
        })
      } else if (opts == 'exportShelveOrder') {
        let params = {
          orderId: row.id,
          type: 1,
        }
        this.$api.orderGetOfferDirectoryDown(params).then((res) => {
          if (res.length == 0) {
            this.$message('暂无CAD数据!')
            return
          }
          let data = [['名称', '编码', '数量', '单价', '小计']]
          let totalAmount = new Decimal(0)
          res.map((el) => {
            el.total = Decimal(el.directoryCount)
              .mul(Decimal(el.directoryFee))
              .toNumber()
            data.push([
              el.directoryName,
              el.directoryCode,
              el.directoryCount,
              el.directoryFee,
              el.total,
            ])
            totalAmount = Decimal(totalAmount).plus(el.total)
          })
          data[data.length + 1] = ['合计:' + totalAmount]
          exportXlsx(data, '营业区', row.storeName)
        })
      } else if (opts == 'costs')
        this.$api['newOrderCosts']({
          id,
        }).then(({ costs = [] }) => {
          this.$quinn.expTable({
            fileName: `${name}-成本`,
            data: [costs],
            columns: [
              { label: '杂项成本', prop: 'additionCost' },
              { label: '产品成本', prop: 'materialCost' },
              { label: '安装成本', prop: 'installCost' },
              { label: '售后成本', prop: 'afterSaleCost' },
              { label: '总成本', prop: 'totalCost' },
              { label: '报价单', prop: 'saveOrder' },
            ],
          })
        })
      else if (opts == 'delete') {
        this.showConfirm(`确认删除【${name}】？`, 'orderOrderDelete', { id })
      } else if (opts == 'exportContract') {
        if (row.contractImg) {
          // this.$refs.pdf.handleOpen(row.contractImg)
          window.open('https://' + row.contractImg, '_blank')
        } else {
          return this.$message.warning('合同还未上传。')
        }
      } else if (opts == 'cancelContract') {
        const r = this.$confirm('确认删除吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).catch(() => null)
        if (r) {
          this.$api.orderCancelContract({ orderId: row.id }).then((res) => {
            if (res == 1) {
              this.$message.success('操作成功!')
              window.location.reload()
            }
          })
        }
      } else if (opts == 'returnInventory') {
        this.showConfirm(
          `确认回滚【${name}】的全部库存吗？`,
          'orderCancelRollbackInventory',
          { orderId: id, areaId: area }
        )
      } else if (opts == 'getCadName') {
        this.showConfirm(
          `确认认领【${name}】的CAD操作吗？`,
          'orderUpdateOrderCadUserId',
          { orderId: id }
        )
      } else if (opts == 'getIsDebt') {
        this.showConfirm(
          `确认【${name}】的欠款已结清吗？`,
          'orderUpdateIsDebt',
          { id: id }
        )
      } else if (
        [
          'storageDetail',
          'goodsDetail',
          'goodsOfferDetail',
          'storageOffer',
        ].includes(opts)
      ) {
        if (opts == 'storageDetail') row.type = 'storage'
        if (opts == 'goodsDetail') row.type = 'goods'
        if (opts == 'goodsOfferDetail') row.type = 'goodsOfferDetail'
        if (opts == 'storageOffer') row.type = 'storageOffer'
        ref = this.$refs.ParseDetailRef
        // classifyDetailRef;
      } else if (opts == 'confirmOrder') {
        ref = this.$refs.confirmRef
      } else if (opts == 'shelves') {
        //货架确认到账
        const data = {
          orderId: row.id,
          flag: 2, //1材料 2货架
        }
        this.$confirm('确认货架到账吗？')
          .then((_) => {
            this.$api.orderUpdatePayStatus(data).then()
            this.$message.success('操作成功！')
            window.location.reload()
          })
          .catch((_) => {
            return
          })
      } else if (opts == 'materialShouMoney') {
        //材料确认到账
        const data = {
          orderId: row.id,
          flag: 1, //1材料 2货架
        }
        this.$confirm('确认材料到账吗？')
          .then((_) => {
            this.$api.orderUpdatePayStatus(data).then()
            this.$message.success('操作成功！')
            window.location.reload()
          })
          .catch((_) => {
            return
          })
      } else ref = this.$refs[map[opts]]
      ref && ref.showDialog(opts, row)
    },
  },
}
</script>

<style lang="less" scoped>
:deep(.el-table__expanded-cell) {
  padding: 0;
}

.table /deep/ .el-image {
  //border: 4px solid #15f5d0;
  width: calc(100% + 12px);
  height: calc(100% + 8px);
  border-radius: 3px;
}
</style>
